/**
 * @param {number[]} startPos
 * @param {number[]} homePos
 * @param {number[]} rowCosts
 * @param {number[]} colCosts
 * @return {number}
 */
 var minCost = function(startPos, homePos, rowCosts, colCosts) {
  const dirs = [[1,0],[0,1],[-1,0],[0,-1]]
  const m = rowCosts.length, n = colCosts.length
  const seen = new Set().add(`${startPos[0]}-${startPos[1]}`)
  let ans = Infinity
  const dfs = (i, j, cost) => {
    if(i === homePos[0] && j === homePos[1]){
      ans = Math.min(ans, cost)
      return
    }
    if(cost > ans) return
    for(let [dx, dy] of dirs){
      let x = i+dx, y = j+dy
      if(x >= 0 && x < m && y >= 0 && y < n && !seen.has(`${x}-${y}`)){
        let now
        if(dy === 0) now = rowCosts[x]
        else now = colCosts[y]
        seen.add(`${x}-${y}`)
        dfs(x, y, cost+now)
        seen.delete(`${x}-${y}`)
      }
    }
  }
  dfs(...startPos, 0)
  return ans === Infinity ? 0 : ans
};